package cn.jilian.sys.web;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.jilian.common.domain.R;
import cn.jilian.entity.Menu;
import cn.jilian.entity.Meta;
import cn.jilian.meta.service.MetaService;
import cn.jilian.sys.domain.MoveInfo;
import cn.jilian.sys.service.MenuService;

@RestController
@RequestMapping("/menu")
public class MenuController {

	@Autowired
	private MenuService menuService;
	@Autowired
	private MetaService metaService;
	@Value("${app.menu.module}")
	private Integer appMenuId;
	
	@RequiresPermissions("system:menu:list")
	@GetMapping("/manage.html")
	public ModelAndView getView(@RequestParam("rankId")Long rankId,HttpSession session) {
		ModelAndView mv=new ModelAndView("gui/tab");
		mv.addObject("title", "菜单管理");
		Meta meta=metaService.getMetaById(rankId);
		mv.addObject("metaData", meta);
		mv.addObject("jsfile","sys.menu_mgr");
		return mv;
	}
	
	
	
	@RequiresPermissions("system:menu:tree")
	@RequestMapping(value="/{id}",method = {RequestMethod.GET,RequestMethod.POST})
	public List<Menu> getMenuTree(@PathVariable(name="id",required=false)Long id) {
		return menuService.getChildren(id,appMenuId);
	}
	
	@RequiresPermissions("system:menu:add")
	@PutMapping("")
	public R addMenu( Menu menu) {
		try {
			menuService.addMenu(menu);
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail;
		}
	}
	
	@RequestMapping(value="/move",method= {RequestMethod.GET,RequestMethod.POST,RequestMethod.OPTIONS})
	public R moveMenu(MoveInfo info) {
		try {
			menuService.updateMenuLoc(info.getId(), info.getFid(), info.getSeq());
			return R.ok("移动成功");
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail("操作失败");
		}
	}
	
	@RequiresPermissions("system:menu:delete")
	@DeleteMapping("/{id}")
	public R deleteMenu(@PathVariable("id")Long id) {
		try {
			menuService.delete(id);
			return R.ok;
		}catch(Exception e) {
			e.printStackTrace();
			return R.fail;
		}
	}
	
	@RequiresPermissions("system:menu:update")
	@PostMapping("")
	public R updateMenuGroup( Menu menu) {
		try {
		menuService.saveMenu(menu);
		return R.ok;
		}catch(Exception e) {

			return R.fail("更新失败");
		}
	}
	

}
